package com.tongyi.lizhishop.activitys;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.allen.library.SuperTextView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.beans.StoreBean;
import com.tongyi.lizhishop.cache.RxCacheManager;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.common.MatisseUtils;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zchu.rxcache.RxCache;
import com.zchu.rxcache.data.CacheResult;
import com.zchu.rxcache.stategy.CacheStrategy;
import com.zhihu.matisse.Matisse;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

public class StoreManagerActivity extends BaseActivity implements RationaleListener {
    private static final int REQUEST_CODE_CHOOSE = 2;
    private static final int GETADDRESS = 5;
    private static final int GETIMAGE = 6;
    private static final int GETDETAILIMAGE = 7;
    private static final int GETSTORETYPE = 8;

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.storeImageHeader)
    ImageView storeImageHeader;
    @BindView(R.id.storeNameSuperTv)
    SuperTextView storeNameSuperTv;
    @BindView(R.id.storeName)
    EditText storeName;
    @BindView(R.id.onsellSuperTv)
    SuperTextView onsellSuperTv;
    @BindView(R.id.onSell)
    EditText onSell;
    @BindView(R.id.contactTeleSuperTv)
    SuperTextView contactTeleSuperTv;
    @BindView(R.id.contactTele)
    EditText contactTele;
    @BindView(R.id.storeType)
    SuperTextView storeType;
    @BindView(R.id.address)
    SuperTextView address;
    @BindView(R.id.viewpageImage)
    SuperTextView viewpageImage;
    @BindView(R.id.textDetail)
    SuperTextView textDetail;
    @BindView(R.id.submit)
    Button submit;
    /**
     * 轮播图返回的数据
     */
    private List<Uri> images = new ArrayList<>();
    /**
     * 图文详情返回的数据
     */
    private List<Uri> detailImages = new ArrayList<>();
    /**
     * 图文详情返回的文字描述
     */
    private String detailText;
    /**
     * 店铺头像
     */
    private Uri imageHeaderUri;
    private PromptDialog prompDialog;

    private boolean storeparamSuccess = false;
    private boolean imageHeaderSuccess = false;
    private String sel_name;
    private String sel_time;
    private String sel_tel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_manager);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "店铺管理");
        prompDialog = PromptDialogUtils.getPrompDialog(this);
        prompDialog.showLoading("加载中", false);
        loadData();
    }

    private void loadData() {
        RxCache rxCache = RxCacheManager.getRxCache();
        APIServiceManager.getInstance().create(StoreApi.class)
                .infoSeller(SPUtils.getInstance().getString("userid"))
                .compose(rxCache.<StoreBean>transformObservable("storemanager", StoreBean.class, CacheStrategy.firstRemote()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<CacheResult<StoreBean>>() {
                    @Override
                    public void onSuccess(CacheResult<StoreBean> value) {
                        prompDialog.dismissImmediately();
                        if ("succ".equals(value.getData().getRe())) {
                            bingView(value.getData());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.dismissImmediately();
                        ToastUtils.showShort("请求数据失败!请检查网络");

                    }
                });

    }

    private void bingView(StoreBean value) {
        StoreBean.ArrayBean array = value.getArray();
        String sel_image = array.getSel_image();
        sel_name = array.getSel_name();
        sel_time = array.getSel_time();
        sel_tel = array.getSel_tel();
        String sel_address = array.getSel_address();
        List<String> images = array.getImages();
        List<String> imagescontent = array.getImagescontent();

        String mername1 = array.getMername1();
        if (!TextUtils.isEmpty(sel_image) && !this.isDestroyed()) {
            Glide.with(this).load(APIServiceManager.server_address + sel_image).into(storeImageHeader);
        }

        storeName.setText(sel_name);
        onSell.setText(sel_time);
        contactTele.setText(sel_tel);
        if (!TextUtils.isEmpty(sel_address)) {
            address.setRightString("已上传");
        }
        if (images != null && images.size() > 0) {
            viewpageImage.setRightString("已上传");
        }

        if (imagescontent != null && imagescontent.size() > 0) {
            textDetail.setRightString("已上传");
        }

        if (!TextUtils.isEmpty(mername1)) {
            storeType.setRightString("已选择");
        }


    }

    @OnClick({R.id.storeNameSuperTv, R.id.submit, R.id.storeImageHeader, R.id.storeType, R.id.address, R.id.viewpageImage, R.id.textDetail, R.id.activity_store_manager})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.storeNameSuperTv:
                //ActivityUtils.startActivity(this, ChangeStoreNameActivity.class);
                break;
            case R.id.storeImageHeader:
                pickImage();
                break;
            case R.id.storeType:
                Intent intent10 = new Intent(this, StoreTypeActivity.class);
                startActivityForResult(intent10, GETSTORETYPE);
                break;
            case R.id.address:
                //权限申请;
                requestLocationPerssion();
                break;
            case R.id.viewpageImage:
                Intent intent1 = new Intent(this, ViewPagerImageActivity.class);
                intent1.putParcelableArrayListExtra("images", (ArrayList<? extends Parcelable>) images);
                startActivityForResult(intent1, GETIMAGE);
                break;
            case R.id.textDetail:
                Intent intent2 = new Intent(this, TextDetailActivity.class);
                intent2.putParcelableArrayListExtra("detailImage", (ArrayList<? extends Parcelable>) detailImages);
                intent2.putExtra("detailText", detailText);
                startActivityForResult(intent2, GETDETAILIMAGE);
                break;
            case R.id.activity_store_manager:
                break;
            case R.id.submit:
                if (checkParams()) {
                    //提交店铺的基本信息
                    prompDialog.showLoading("请等待", false);
                    submitData();
                    //提交店铺的头像
                    submitData3();
                }
                break;
        }
    }

    private void requestLocationPerssion() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Permission.LOCATION)
                .rationale(this)
                .callback(this)
                .start();
    }


    /**
     * 提交店铺的头像
     */
    private void submitData3() {
        if (imageHeaderUri == null || imageHeaderSuccess) {
            imageHeaderSuccess = true;
            checkSuccess();
            return;
        }

        PostRequest<String> params = OkGo.<String>post(APIServiceManager.server_address + "/frontend.php/SelSeller/saveImage")
                .params("selid", SPUtils.getInstance().getString("userid"));
        ArrayList<File> files = new ArrayList<>(images.size());
        files.add(new File(getRealPathFromURI(this, imageHeaderUri)));
        params.addFileParams("image", files);
        params.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Gson gson = new Gson();
                CommonResonseBean commonResonseBean = gson.fromJson(response.body().toString(), CommonResonseBean.class);
                LogUtils.w(response.body());
                if ("succ".equals(commonResonseBean.getRe())) {
                    imageHeaderSuccess = true;
                } else {
                    imageHeaderSuccess = false;
                }
                checkSuccess();
            }


        });
    }


    private synchronized void checkSuccess() {
        if (imageHeaderSuccess && storeparamSuccess) {
            prompDialog.showSuccess("数据提交成功", false);
            Intent data = new Intent();
            data.putExtra("need_reload_flag", true);
            setResult(RESULT_OK, data);
            finish();
        } else {
            prompDialog.showError("提交失败,请重试");
        }
    }


    /**
     * 提交店铺的基本信息
     */
    private void submitData() {
        if (storeparamSuccess || notChange()) {
            storeparamSuccess = true;
            checkSuccess();
            return;
        }

        APIServiceManager.getInstance().create(StoreApi.class)
                .saveSeller(SPUtils.getInstance().getString("userid"), storeName.getText().toString(), onSell.getText().toString(), contactTele.getText().toString())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<CommonResonseBean>() {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        LogUtils.w("value", value);
                        if ("succ".equals(value.getRe())) {
                            storeparamSuccess = true;
                        } else {
                            storeparamSuccess = false;
                        }
                        checkSuccess();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        LogUtils.w("出错啦");
                        ToastUtils.showShort(e.getMessage());
                        storeparamSuccess = false;
                        checkSuccess();
                    }
                });

    }

    /**
     * 判断数据是否发生变动
     *
     * @return
     */
    private boolean notChange() {
        if (String.valueOf(storeName.getText()).equals(sel_name) && String.valueOf(onSell.getText()).equals(sel_time) && String.valueOf(contactTele.getText()).equals(sel_tel)) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkParams() {
        if (notChange() && imageHeaderUri == null) {
            ToastUtils.showShort("请编辑后再保存");
            return false;
        }
        return true;
    }

    private void pickImage() {
        // 在Activity：
        AndPermission.with(this)
                .requestCode(100)
                .permission(Permission.STORAGE)
                .rationale(this)
                .callback(this)
                .start();


    }


    public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result;
        Cursor cursor = context.getContentResolver().query(contentURI,
                new String[]{MediaStore.Images.ImageColumns.DATA},//
                null, null, null);
        if (cursor == null) result = contentURI.getPath();
        else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(index);
            cursor.close();
        }
        return result;
    }

    // 成功回调的方法，用注解即可，这里的300就是请求时的requestCode。
    @PermissionYes(100)
    private void getPermissionYes(List<String> grantedPermissions) {
        if (grantedPermissions.get(0).equals(Permission.STORAGE[0])) {
            selectPicFromLocal();
        } else {
            Intent intent = new Intent(this, AddressActivity.class);
            startActivityForResult(intent, GETADDRESS);
        }
    }

    @PermissionNo(100)
    private void getPermissionNo(List<String> deniedPermissions) {

        if (deniedPermissions.get(0).equals(Permission.STORAGE[0])) {
            ToastUtils.showShort("请给予程序读取存储卡权限应用才能读取图片哦!");
        } else {
            ToastUtils.showShort("没有定位权限,无法选择地区地址!");

        }
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
      /*  AlertDialog.newBuilder(this)
                .setTitle("提示")
                .setMessage("选择图片需要给程序读取内存的权限").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                rationale.resume();
                dialog.dismiss();
            }
        });*/

    }

    private void selectPicFromLocal() {
        MatisseUtils.pickImage(this, 1, REQUEST_CODE_CHOOSE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //更改店铺头像
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);
            mSelected = Matisse.obtainResult(data);
            for (final Uri uri : mSelected) {
                Glide.with(this).load(uri).centerCrop().into(storeImageHeader);
                imageHeaderUri = uri;
            }
        }
        //返回地址
        if (data != null && requestCode == GETADDRESS && resultCode == RESULT_OK) {
            int status = data.getIntExtra("status", -1);
            if (status == 1) {
                address.setRightString("已上传");
            }
        }

        //返回轮播图

        if (data != null && requestCode == GETIMAGE && resultCode == RESULT_OK) {
            int status = data.getIntExtra("status", -1);
            if (status == 1) {
                viewpageImage.setRightString("已上传");
            }
        }
        //返回图文详情

        if (data != null && requestCode == GETDETAILIMAGE && resultCode == RESULT_OK) {
            int status = data.getIntExtra("status", -1);
            if (status == 1) {
                textDetail.setRightString("已上传");
            }
        }

        //返回店铺类型

        if (data != null && requestCode == GETSTORETYPE && resultCode == RESULT_OK) {
            int status = data.getIntExtra("status", -1);
            if (status == 1) {
                storeType.setRightString("已选择");
            }
        }

    }

}
